﻿
using OF.Utility.Logging;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace ULog.Filters
{
    /// <summary>
    /// 行为记录
    /// </summary>
    public class APIActionFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 在调用操作方法之前发生
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
        
            //记录行为日志
            ActionLog log = new ActionLog();
            log.APPVersion = GetHeaderValue(actionContext, "appversion");
            log.ClientId = GetHeaderValue(actionContext, "appclientid");
            log.Imei = GetHeaderValue(actionContext, "appimei");
            log.Moble = GetHeaderValue(actionContext, "appmobile");
            log.Model = GetHeaderValue(actionContext, "appmodel");
            log.PlatformID = 1;
            log.PlatformVersion = GetHeaderValue(actionContext, "apposversion");
            log.Token = GetHeaderValue(actionContext, "apptoken");
            log.UA = HttpContext.Current.Request.UserAgent;
            log.Uuid = GetHeaderValue(actionContext, "appuuid");
            log.Vendor = GetHeaderValue(actionContext, "appvendor");
            string userId = GetHeaderValue(actionContext, "appuser");
            log.UserID = string.IsNullOrEmpty(userId) ? 0 : Convert.ToInt32(userId);
            log.RequestMethod = actionContext.Request.Method.Method;
            if (log.RequestMethod.Equals("POST", StringComparison.Ordinal))
            {
                log.PostData = GetPostData(actionContext);
            }
            log.RequestUrl = actionContext.Request.RequestUri.AbsoluteUri;
            log.CreatedDate = DateTime.Now;
            log.ClientIP = OF.Utility.IPHelper.IPAddress;
            Log4netLog.Info(log);
            base.OnActionExecuting(actionContext);
        }

        /// <summary>
        /// 获取制定的header值
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetHeaderValue(HttpActionContext actionContext, string name)
        {
            IEnumerable<string> headers;
            if (actionContext.Request.Headers.TryGetValues(name, out headers))
            {
                return headers.FirstOrDefault();

            }
            return "";
        }

        /// <summary>
        /// 获取post数据
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected string GetPostData(HttpActionContext actionContext)
        {
            string str = "";
            if (actionContext.Request.Content.IsMimeMultipartContent())
            {
                return "";
            }
            try
            {
                if (actionContext.Request.Content.IsFormData())
                {
                    NameValueCollection nv = actionContext.Request.Content.ReadAsFormDataAsync().Result;
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in nv.AllKeys)
                    {
                        sb.AppendFormat("key:{0},value:{1},", item, nv[item]);
                    }
                    str = sb.ToString();
                }
                else
                {
                    Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
                    if (stream != null && stream.Length > 0)
                    {
                        stream.Position = 0; //当你读取完之后必须把stream的读取位置设为开始
                        using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
                        {
                            str = reader.ReadToEnd().ToString();
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                // Log4netLog.Fatal(ex.Message);
            }
            return str;
        }
    }
}